package LeetCode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName interview
 * @Description: TODO
 * @date ${DAT}21:57
 */
public class LeetCode841 {
    boolean[] vis;
    int num;
    // 并查集问题 孤岛问题
    public boolean canVisitAllRooms(List<List<Integer>> rooms) {
        int n = rooms.size();
        num = 0;
        vis = new boolean[n];
        dfs(rooms,0);
        return num == n;
    }

    private void dfs(List<List<Integer>> rooms, int i) {
        vis[i] = true;
        num++;
        for (Integer integer : rooms.get(i)) {
            if (!vis[integer]){
                dfs(rooms,integer);
            }
        }
    }

    public boolean canVisitAllRooms2(List<List<Integer>> rooms) {
        int n = rooms.size(), num = 0;
        boolean[] vis = new boolean[n];
        Queue<Integer> que = new LinkedList<Integer>();
        vis[0] = true;
        que.offer(0);
        while (!que.isEmpty()) {
            int x = que.poll();
            num++;
            for (int it : rooms.get(x)) {
                if (!vis[it]) {
                    vis[it] = true;
                    que.offer(it);
                }
            }
        }
        return num == n;
    }

    public static void main(String[] args) {
        List<List<Integer>> rooms = new ArrayList<>();
        List<Integer> room = new ArrayList<>();
        room.add(6);
        room.add(7);
        room.add(8);;

        List<Integer> room2 = new ArrayList<>();
        room2.add(5);
        room2.add(4);
        room2.add(9);

        List<Integer> room3 = new ArrayList<>();


        List<Integer> room4 = new ArrayList<>();
        room4.add(8);

        List<Integer> room5 = new ArrayList<>();
        room5.add(4);

        List<Integer> room6 = new ArrayList<>();

        List<Integer> room7 = new ArrayList<>();
        room7.add(1);
        room7.add(9);
        room7.add(2);
        room7.add(3);

        List<Integer> room8 = new ArrayList<>();
        room8.add(7);

        List<Integer> room9 = new ArrayList<>();
        room9.add(6);
        room9.add(5);

        List<Integer> room10 = new ArrayList<>();
        room10.add(2);
        room10.add(3);
        room10.add(1);


        rooms.add(room);
        rooms.add(room2);
        rooms.add(room3);
        rooms.add(room4);
        rooms.add(room5);
        rooms.add(room6);
        rooms.add(room7);
        rooms.add(room8);
        rooms.add(room9);
        rooms.add(room10);
        System.out.println(new LeetCode841().canVisitAllRooms2(rooms));
    }
}
